package com.lzy.crm.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.JsonObject;
import com.lzy.crm.base.date.DateUtil;
import com.lzy.crm.base.mybatis.BaseMapper;
import com.lzy.crm.base.page.PageQuery;
import com.lzy.crm.base.service.BaseServiceImpl;
import com.lzy.crm.base.util.JsonUtil;
import com.lzy.crm.base.util.StringUtil;
import com.lzy.crm.dao.CardFlowMapper;
import com.lzy.crm.dao.OrderMapper;
import com.lzy.crm.dao.PpUserMapper;
import com.lzy.crm.dao.ProfitRuleMapper;
import com.lzy.crm.dao.UserMapper;
import com.lzy.crm.dao.criteria.CardFlowCriteria;
import com.lzy.crm.domain.CardFlow;
import com.lzy.crm.domain.Order;
import com.lzy.crm.domain.PpUser;
import com.lzy.crm.domain.Profit;
import com.lzy.crm.domain.ProfitRule;
import com.lzy.crm.domain.User;
import com.lzy.crm.service.CardFlowService;
import com.lzy.crm.service.PpUserService;
import com.lzy.crm.service.ProfitService;
import com.lzy.crm.service.UserService;
import com.lzy.crm.util.OrderConstants;
import com.lzy.crm.util.UserConstants;
import com.lzy.crm.vo.CardFlowVo;
import com.lzy.crm.vo.PlayerInfo;
import com.lzy.crm.wechat.consts.WechatPayProperties;
import com.lzy.crm.wechat.util.WeixinUtil;



@Service("cardFlowService")
public class CardFlowServiceImpl extends BaseServiceImpl<CardFlow,CardFlowCriteria> implements CardFlowService {

	Logger logger= Logger.getLogger(CardFlowServiceImpl.class);
	
	@Resource
	private CardFlowMapper cardFlowMapper;
	
	@Resource
	private PpUserService puserService;
	
	@Resource
	private PpUserMapper puserMapper;
	
	@Resource
	private OrderMapper orderMapper;
	
	@Resource
	private ProfitService profitService;
	
	@Resource
	private ProfitRuleMapper profitRuleMapper ;
	
	
	/**绑定微信回调线程池*/
	private static ThreadPoolExecutor downloadImgThreadPool;
	
	@Override
	public BaseMapper<CardFlow, CardFlowCriteria> getBaseMapper() {
		return cardFlowMapper;
	}

	@Override
	public List<CardFlow> getCardFlowList(String aId, String bId,PageQuery pageQuery) {
		return cardFlowMapper.getCardFlowList(aId, bId, pageQuery);
	}

	@Override
	public List<CardFlowVo> getCardFlowVoList(String aId, String bId,
			PageQuery pageQuery) {
		List<CardFlowVo> cardFlowVoList =new ArrayList<CardFlowVo>();
		List<CardFlow> cardFlowList = cardFlowMapper.getCardFlowList(aId, bId, pageQuery);
		for (CardFlow cardFlow : cardFlowList) {
			CardFlowVo cardFlowVo= JsonUtil.fromJson(JsonUtil.toJson(cardFlow), CardFlowVo.class);
			cardFlow.setCard(cardFlow.getCard()+cardFlow.getAwardCard());  // 充值数据 等于购买金额 + 赠送金额
			//User user = userMapper.getById(cardFlow.getAId());
			/*if(user!=null){
				cardFlowVo.setPhone(user.getPhone());
			}*/
			cardFlowVoList.add(cardFlowVo);
		}
		return cardFlowVoList;
	}
	
	
	/**
	 * 用户给玩家添加房卡接口
	 */
	@Override
	@Transactional
	public String newBuyCard(PlayerInfo playerInfo, User user)throws Exception {
		
		String resultCode ="01";
		Integer userTotalCard = 0;  //玩家总卡数
		/*PlayerInfo sellPlayerInfo = userMapper.getPlayerInfo(user.getGameUserId(),null);
		PlayerInfo newplayerInfo = userMapper.getPlayerInfo(playerInfo.getGameId(),null);
		if(sellPlayerInfo == null){
			resultCode="03";  // 代理信息有误
			return resultCode;
		}
		if(newplayerInfo==null){
			resultCode="04"; // 玩家信息有误
			return resultCode;
		}
		// 买的总卡数 包括赠送的和购买的卡数
		Integer totalCard = playerInfo.getCard()+playerInfo.getAwardCard();
		userTotalCard= sellPlayerInfo.getInsureScore();
		if(userTotalCard>= totalCard){
			// 卖家剩余卡数
			Integer surplusCard=userTotalCard-totalCard;
			// 扣除代理房卡
			userMapper.sellPlayerCard(sellPlayerInfo.getUserId(), surplusCard);;
			// 给玩家加房卡
			userMapper.addPlayerCard(newplayerInfo.getUserId(), totalCard);
			// 生成记录
			CardFlow cardFlow =new CardFlow();
			cardFlow.setAId(sellPlayerInfo.getGameId());
			cardFlow.setAName(user.getUserName());
			cardFlow.setACard(surplusCard);
			cardFlow.setBId(newplayerInfo.getGameId());
			cardFlow.setBName(newplayerInfo.getNickName());
			cardFlow.setCard(playerInfo.getCard());
			cardFlow.setAwardCard(playerInfo.getAwardCard());
			cardFlow.setBeforeCard(newplayerInfo.getInsureScore());
			cardFlow.setAfterCard(newplayerInfo.getInsureScore()+totalCard);
			cardFlow.setFunc(playerInfo.getFunc());
			cardFlow.setRemark(playerInfo.getRemark());
			cardFlow.setType(UserConstants.CARD_TYPE_PLAYER);
			cardFlow.setCreateTime(new Date());
			cardFlowMapper.insertSelective(cardFlow);
			logger.info("代理商ID:" +sellPlayerInfo.getGameId() +"给玩家 ID:"+playerInfo.getGameId()+"充值了房卡"+totalCard);
		}else{
			// 返回错误，卖出去的卡 大于代理商能卖的卡数
			resultCode="02";
		}*/
		return resultCode;
	}
	
	
	
	
	/**
	 * 用户给玩家添加房卡接口
	 */
	@Override
	@Transactional
	public String buyCard(PlayerInfo playerInfo, User user)throws Exception {
		
		String resultCode ="01";
		Integer userTotalCard = 0;  //玩家总卡数
		/*User newUser= userMapper.getById(user.getId());
		PlayerInfo newplayerInfo = userMapper.getPlayerInfo(playerInfo.getGameId(),null);
		if(newUser==null){
			resultCode="03";  // 代理信息有误
			return resultCode;
		}
		if(newplayerInfo==null){
			resultCode="04"; // 玩家信息有误
			return resultCode;
		}
		// 买的总卡数 包括赠送的和购买的卡数
		Integer totalCard = playerInfo.getCard()+playerInfo.getAwardCard();
		userTotalCard= newUser.getTotalCard();
		if(userTotalCard>= totalCard){
			newUser.setTotalCard(userTotalCard-totalCard);
			// 扣除代理房卡
			userMapper.updateByPrimaryKeySelective(newUser);
			// 给玩家加房卡
			userMapper.addPlayerCard(newplayerInfo.getUserId(), totalCard);
			// 生成记录
			CardFlow cardFlow =new CardFlow();
			cardFlow.setAId(newUser.getId());
			cardFlow.setAName(newUser.getUserName());
			cardFlow.setACard(newUser.getTotalCard());
			cardFlow.setBId(newplayerInfo.getGameId());
			cardFlow.setBName(newplayerInfo.getNickName());
			cardFlow.setCard(playerInfo.getCard());
			cardFlow.setAwardCard(playerInfo.getAwardCard());
			cardFlow.setBeforeCard(newplayerInfo.getInsureScore());
			cardFlow.setAfterCard(newplayerInfo.getInsureScore()+totalCard);
			cardFlow.setFunc(playerInfo.getFunc());
			cardFlow.setRemark(playerInfo.getRemark());
			cardFlow.setType(UserConstants.CARD_TYPE_PLAYER);
			cardFlow.setCreateTime(new Date());
			cardFlowMapper.insertSelective(cardFlow);
			logger.info("代理商ID:" +newUser.getId() +"给玩家 UserId:"+playerInfo.getUserId()+"- gameID:"+playerInfo.getGameId()+"充值了房卡"+totalCard);
		}else{
			// 返回错误，卖出去的卡 大于代理商能卖的卡数
			resultCode="02";
		}*/
		return resultCode;
	}

	/**
	 * 用户给代理商充值方法
	 * @param playerInfo
	 * @param user
	 * @return
	 */
	@Override
	@Transactional
	public String buyCardByUser(PlayerInfo playerInfo,User user,User adduser)throws Exception{
		String resultCode ="01";
		Integer userTotalCard = 0;  //出售着总卡数
		Integer addUserTotalCard = 0;   // 购买者卡数
		/*User newUser= userMapper.getById(user.getId());
		// 买的总卡数 包括赠送的和购买的卡数
		Integer totalCard = playerInfo.getCard()+playerInfo.getAwardCard();
		userTotalCard= newUser.getTotalCard();
		addUserTotalCard = adduser.getTotalCard()==null?0:adduser.getTotalCard();
		if(userTotalCard>= totalCard){
			newUser.setTotalCard(userTotalCard-totalCard);
			// 扣除代理房卡
			userMapper.updateByPrimaryKeySelective(newUser);
			// 给代理商加房卡
			adduser.setTotalCard(addUserTotalCard+totalCard);
			 
			userMapper.updateByPrimaryKeySelective(adduser);
			// 生成记录
			CardFlow cardFlow =new CardFlow();
			cardFlow.setAId(newUser.getId());
			cardFlow.setAName(newUser.getUserName());
			cardFlow.setACard(newUser.getTotalCard());
			cardFlow.setBId(adduser.getId());
			cardFlow.setBName(adduser.getUserName());
			cardFlow.setCard(playerInfo.getCard());
			cardFlow.setAwardCard(playerInfo.getAwardCard());
			cardFlow.setBeforeCard(addUserTotalCard);
			cardFlow.setAfterCard(addUserTotalCard+totalCard);
			cardFlow.setFunc(playerInfo.getFunc());
			cardFlow.setRemark(playerInfo.getRemark());
			cardFlow.setType(UserConstants.CARD_TYPE_USER);;
			cardFlow.setCreateTime(new Date());
			cardFlowMapper.insertSelective(cardFlow);
			logger.info("上级代理商ID:" +newUser.getId() +"给代理商 UserId:"+playerInfo.getUserId()+"充值了房卡"+totalCard);
		}else{
			// 返回错误，卖出去的卡 大于代理商能卖的卡数
			resultCode="02";
		}*/
		return resultCode;
	}
	
	/**
	 *微信支付处理接口
	 */
	@Override
	@Transactional
	public String buyCardByWechat(final Order order)throws Exception{
		try{
			final PpUser puser = puserService.getPpUser(order.getGameId().toString());
			//final User user = userService.getUserByUnionid(order.getUnionid());
			if(puser!=null){
				logger.error("支付成功，玩家ID ："+order.getGameId() +" 支付前饭卡数:"+puser.getRoomcard() +
						"   订单号："+order.getOrId()+ "  充值"+order.getOrNub());
				// 给玩家添加房卡
				Integer beforeCard = puser.getRoomcard();
				
				order.setStatus(OrderConstants.ORDER_STATUS_SUCCEED);
				order.setOrTime(new Date());
				// 修改订单状态
				orderMapper.updateByPrimaryKeySelective(order);
				
				
				//  添加玩家积分
				puserMapper.updateByPrimaryKeySelective(puser);
				// 修改卡流水  生成记录
				CardFlow cardFlow =new CardFlow();
				cardFlow.setAId(0);
				cardFlow.setAName("微信购买");
				cardFlow.setACard(0);
				cardFlow.setBId(puser.getUid());
				cardFlow.setBName(puser.getNickname());
				cardFlow.setCard(order.getOrNub());
				cardFlow.setAwardCard(0);
				cardFlow.setBeforeCard(beforeCard);
				cardFlow.setAfterCard(puser.getRoomcard());
				cardFlow.setFunc(0);
				cardFlow.setRemark("微信支付购买");
				cardFlow.setType(UserConstants.CARD_TYPE_WECHAT);;
				cardFlow.setCreateTime(new Date());
				cardFlowMapper.insertSelective(cardFlow);
				
				//是否是代理充值， 是走代理分润流程
				boolean is_tgds = puser.getUserLevel()==1;
				Integer puserId = puser.getFrontUid();  // 代理商分成一级
				// 分成方法
				if(puserId!=null){
					// 默认分成模式
					Integer ratio = 0;// 代理商分成比例
					//上级代理
					/*final User puser = puserService.getById(puserId);
					if(puser!=null){
						// 一级分红模式    用户等级不为空且是代理商
						if(StringUtil.isNotEmpty(puser.getUserLevel())&&(StringUtil.equals(puser.getUserType(), UserConstants.USER_TYPE_AGENT)||
								StringUtil.equals(puser.getUserType(), UserConstants.USER_TYPE_MANAGE))){
							ProfitRule profitRule=profitRuleMapper.getById(puser.getUserLevel());
							if(profitRule!=null){
								String ratios []= is_tgds?profitRule.getPrifitValue().split(":"):profitRule.getPrifitAgent().split(":");
								if(ratios.length>=1){
									ratio=Integer.parseInt(ratios[0]);
									if(ratio.intValue()!=0){
										// 满足分红条件
										channerl( ratio,  puser  , order, user ,1);
										
										final Integer pratio =  ratio;
										
										*//*************回调线程  开始  ***//*
										Runnable callBackThread = new Runnable() {
											@Override
											public void run() {
												// 推送消息微信模板通知
												retParentMes( user , puser, order , pratio);
											}
										};
										if (downloadImgThreadPool == null) {
											synchronized(this) {
												if (downloadImgThreadPool == null) {
													downloadImgThreadPool = new ThreadPoolExecutor(5, 10000, 120, 
															TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10000));
												}
											}
										}
										downloadImgThreadPool.execute(callBackThread);
										*//***** 结束  ********//*
										// 推送通知
									}
								}
							}
						}
						// 二级分红模式 
						Integer ppuserId = puser.getParentId();
						if(ppuserId!=null){
							User ppuser = userService.getById(ppuserId);
							// 用户正常状态才可以享受二级分润
							if(ppuser!=null&&StringUtil.equals(ppuser.getStatus(),UserConstants.USER_STATUS_NORMAL)){
								if(StringUtil.isNotEmpty(ppuser.getUserLevel())&&(StringUtil.equals(ppuser.getUserType(), UserConstants.USER_TYPE_AGENT)||
										StringUtil.equals(ppuser.getUserType(), UserConstants.USER_TYPE_MANAGE))){
									ProfitRule pprofitRule=profitRuleMapper.getById(ppuser.getUserLevel());
									if(pprofitRule!=null){
										String ratios []= is_tgds?pprofitRule.getPrifitValue().split(":"):pprofitRule.getPrifitAgent().split(":");
										if(ratios.length>=2){
											ratio=Integer.parseInt(ratios[1]);
											if(ratio.intValue()!=0){
												channerl( ratio,  ppuser  , order, user ,2);
											}
										}
									}
								}
							}
						}
						
					}else{
						logger.error("订单ID:"+order.getId()+" 一级分红 未查到代理商ID:"+puserId +"相关信息   分红失败  ");
					}*/
				}
			}else{
				logger.error("充卡失败，订单Id："+order.getId()+"  玩家ID gameId："+ order.getGameId()+"  充值数量："+ order.getOrNub());
			}
			
		}catch(Exception e){
			logger.error("充卡失败，订单Id："+order.getId()+"  玩家ID gameId："+ order.getGameId()+"  充值数量："+ order.getOrNub());
			throw e;
		}
		return "0";
	}
	
	public Integer channerl(Integer ratio,PpUser puser  ,Order order,User user ,Integer lvl)throws Exception{
		// 代理商 或者管理员 算提成
		//if(StringUtil.equals(puser.getStatus(), UserConstants.USER_STATUS_NORMAL)){
			// 生成分润记录
			double ticeng = order.getOrMoney()*ratio*0.01 ;
			// 计算提成
			/*puser.setTiceng(puser.getTiceng()+ticeng);
			puserService.updateByPrimaryKeySelective(puser);
			logger.info("玩家gameId: "+user.getGameUserId()+", 充值金额: "+order.getOrMoney()+ ", " + lvl+
					"级代理玩家gameId: "+puser.getGameUserId() +", 获得提成：" +ticeng);*/
			// 生成提成记录
			Profit profit =new Profit();
			//profit.setuId(user.getId());
			//profit.setGameId(user.getGameUserId());
			profit.setUserName(user.getUserName());
			profit.setOutUserName(user.getOutUserName());
			profit.setOrId(order.getOrId());
			profit.setOrNub(order.getOrNub());
			profit.setOrMoney(order.getOrMoney());
			profit.setProfitSum(ticeng);
			profit.setProfitLevel(lvl.toString());
			profit.setParentUid(puser.getUid());
			profit.setCreateTime(new Date());
			profitService.insertSelective(profit);
		//}
		return puser!=null?puser.getFrontUid():null;
	}
	
	
	
	
	/**
	 * 查询玩家流出房卡总数
	 * @param userId
	 * @param startTime
	 * @param entTime
	 * @return
	 */
	public Integer getCardinflow(int userId,String startTime,String entTime){
		return cardFlowMapper.getCardinflow(userId, startTime, entTime);
	}
	
	/**
	 * 
	 * @param user
	 * @param prarentUser
	 * @param order
	 * @param ratio
	 */
	public void retParentMes(User user ,User prarentUser,Order order ,Integer ratio){
		
		
		//String titile = " 亲爱的 "+prarentUser.getOutUserName()+" ,【"+nickName+"】 已通过扫描您的分享二维码成为您的粉丝新用户，您已获赠"+roomCardMenInvited+"张房卡。";
		/*String titile = "亲爱的Lee，您邀请的宾友棋牌用户66366刚刚购买了50元房卡，您已获得25元分红，邀请的用户越多，收益越多！"
		+ "可在郴州互娱公众号查看分红明细，活动期间分红满100元即可在每月8号和28号联系微信客服byqp518领取，感谢您的支持！";*/
		java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");  
		String profitMoney =df.format(order.getOrMoney()*ratio*0.01) ;
		String titile = "   亲爱的  "+prarentUser.getOutUserName()+" ，您邀请的用户【"+user.getOutUserName()+"】 刚刚购买了"+order.getOrMoney()+"元房卡，您已获得 "+profitMoney+" 元分红！"
				+ "可在公众号查看分红明细，活动期间分红满18元即可在每月8号、18号、28号联系微信客服xianle6688领取，感谢您的支持！";
		String inscribe ="分享越多，收获越多！感谢您的支持！";
		//模板消息ID
		String template_id = "OYGeIP0g7Zb3vIIaVV4IIRw9ZCocEkRcV3GRv-5ddak";//
		String access_token = WeixinUtil.getAccessToken(WechatPayProperties.getAppId(),WechatPayProperties.getAppSecret()).getToken();
		//发送模板消息
		String send = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
		String sendJosn = "{\"touser\":\""+prarentUser.getOpenid()+"\", \"template_id\":\""+template_id+"\" " +
		           ",\"data\":{ "+
						"\"first\": {  "+
							"\"value\":\"  "+titile+" \", "+
							"\"color\":\"#173177\" "+
		                  " }, "+
		                   "\"keyword1\":{ "+
		                       "\"value\":\""+ profitMoney  +" \", "+
		                       "\"color\":\"#173177\" "+
		                 "  }, "+
		                   "\"keyword2\":{ "+
		                       "\"value\":\" "+ df.format(prarentUser.getTiceng()) +" \", "+
		                       "\"color\":\"#173177\" "+
		                 "  }, "+
		                   "\"keyword3\":{ "+
		                       "\"value\":\""+DateUtil.getCurrentLongTime()+" \", "+
		                       "\"color\":\"#173177\" "+
		                 "  }, "+
		                 "  \"remark\":{ "+
		                 "       \"value\":\""+inscribe+"\", "+
		                 "       \"color\":\"#173177\" "+
		                 "   } } }"; 
		
		JsonObject sendJson = WeixinUtil.HttpRequest( send , "POST", sendJosn);
		logger.info("推送消息返回结果:" + sendJson);
		
	}
	
	
	
	/**
	 * 用户给玩家添加房卡接口
	 */
	@Override
	@Transactional
	public String buyAgentCard(PlayerInfo playerInfo,User user,Integer orMoney)throws Exception {
		
		String resultCode ="01";
		Integer userTotalCard = 0;  //玩家总卡数
		/*PlayerInfo sellPlayerInfo = userMapper.getPlayerInfo(user.getGameUserId(),null);
		PlayerInfo newplayerInfo = userMapper.getPlayerInfo(playerInfo.getGameId(),null);
		if(sellPlayerInfo == null){
			resultCode="03";  // 代理信息有误
			return resultCode;
		}
		if(newplayerInfo==null){
			resultCode="04"; // 玩家信息有误
			return resultCode;
		}
		
		final Order order=new Order();
		order.setOrMoney(orMoney.doubleValue());
		// 买的总卡数 包括赠送的和购买的卡数
		Integer totalCard = playerInfo.getCard()+playerInfo.getAwardCard();
		userTotalCard= sellPlayerInfo.getInsureScore();
		if(userTotalCard>= totalCard){
			// 卖家剩余卡数
			Integer surplusCard=userTotalCard-totalCard;
			// 扣除代理房卡
			userMapper.sellPlayerCard(sellPlayerInfo.getUserId(), surplusCard);;
			// 给玩家加房卡
			userMapper.addPlayerCard(newplayerInfo.getUserId(), totalCard);
			// 生成记录
			CardFlow cardFlow =new CardFlow();
			cardFlow.setAId(sellPlayerInfo.getGameId());
			cardFlow.setAName(user.getUserName());
			cardFlow.setACard(surplusCard);
			cardFlow.setBId(newplayerInfo.getGameId());
			cardFlow.setBName(newplayerInfo.getNickName());
			cardFlow.setCard(playerInfo.getCard());
			cardFlow.setAwardCard(playerInfo.getAwardCard());
			cardFlow.setBeforeCard(newplayerInfo.getInsureScore());
			cardFlow.setAfterCard(newplayerInfo.getInsureScore()+totalCard);
			cardFlow.setFunc(playerInfo.getFunc());
			cardFlow.setRemark(playerInfo.getRemark());
			cardFlow.setType(UserConstants.CARD_TYPE_PLAYER);
			cardFlow.setCreateTime(new Date());
			cardFlowMapper.insertSelective(cardFlow);
			
			logger.error("充卡成功，玩家ID ：" + newplayerInfo.getGameId() +" 支付前饭卡数:"+newplayerInfo.getInsureScore() +
					"   订单号："+cardFlow.getId()+ "  充值"+ orMoney);
			
			//非推广大使充值模式
			boolean is_tgds = StringUtil.equals(user.getUserLevel(), UserConstants.USER_LEVEL_TGDS);
			List<User> userBuyList = userMapper.getUserListByGameId(newplayerInfo.getGameId().toString());
			final User userBuy = userBuyList!=null&&userBuyList.size()>0?userBuyList.get(0):null;
			Integer puserId = userBuy.getParentId();  // 代理商分成一级
			// 分成方法
			if(puserId!=null){
				// 默认分成模式
				Integer ratio = 0;// 代理商分成比例
				//上级代理
				final User puser = userService.getById(puserId);
				if(puser!=null){
					// 一级分红模式    用户等级不为空且是代理商
					if(StringUtil.isNotEmpty(puser.getUserLevel())&&(StringUtil.equals(puser.getUserType(), UserConstants.USER_TYPE_AGENT)||
							StringUtil.equals(puser.getUserType(), UserConstants.USER_TYPE_MANAGE))){
						ProfitRule profitRule=profitRuleMapper.getById(puser.getUserLevel());
						if(profitRule!=null){
							String ratios []= is_tgds?profitRule.getPrifitValue().split(":"):profitRule.getPrifitAgent().split(":");
							if(ratios.length>=1){
								ratio=Integer.parseInt(ratios[0]);
								if(ratio.intValue()!=0){
									// 满足分红条件
									channerl( ratio,  puser , userBuy, cardFlow, orMoney ,1);
									
									// 满足分红条件
									final Integer pratio =  ratio;
									
									*//*************回调线程  开始  ***//*
									Runnable callBackThread = new Runnable() {
										@Override
										public void run() {
											// 推送消息微信模板通知
											retParentMes( userBuy , puser, order , pratio);
										}
									};
									if (downloadImgThreadPool == null) {
										synchronized(this) {
											if (downloadImgThreadPool == null) {
												downloadImgThreadPool = new ThreadPoolExecutor(5, 10000, 120, 
														TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10000));
											}
										}
									}
									downloadImgThreadPool.execute(callBackThread);
									*//***** 结束  ********//*
									
									
								}
							}
						}
					}
					// 二级分红模式 
					Integer ppuserId = puser.getParentId();
					if(ppuserId!=null){
						User ppuser = userService.getById(ppuserId);
						// 用户正常状态才可以享受二级分润
						if(ppuser!=null&&StringUtil.equals(ppuser.getStatus(),UserConstants.USER_STATUS_NORMAL)){
							if(StringUtil.isNotEmpty(ppuser.getUserLevel())&&(StringUtil.equals(ppuser.getUserType(), UserConstants.USER_TYPE_AGENT)||
									StringUtil.equals(ppuser.getUserType(), UserConstants.USER_TYPE_MANAGE))){
								ProfitRule pprofitRule=profitRuleMapper.getById(ppuser.getUserLevel());
								if(pprofitRule!=null){
									String ratios []= is_tgds?pprofitRule.getPrifitValue().split(":"):pprofitRule.getPrifitAgent().split(":");
									if(ratios.length>=2){
										ratio=Integer.parseInt(ratios[1]);
										if(ratio.intValue()!=0){
											channerl( ratio,  ppuser  ,userBuy, cardFlow, orMoney ,2);
										}
									}
								}
							}
						}
					}
				}else{
					logger.error(" 一级分红 未查到代理商ID:"+puserId +"相关信息   分红失败  ");
				}
			}
		
			
			
		}else{
			// 返回错误，卖出去的卡 大于代理商能卖的卡数
			resultCode="02";
		}*/
		return resultCode;
	}
	
	
	
	
	public Integer channerl(Integer ratio,PpUser puser ,PpUser user , CardFlow cardFlow , Integer orMoney ,Integer lvl)throws Exception{
		// 代理商 或者管理员 算提成
		//if(StringUtil.equals(puser.getStatus(), UserConstants.USER_STATUS_NORMAL)){
			// 生成分润记录
			double ticeng = orMoney * ratio*0.01 ;
			// 计算提成
			puser.setBackgold(puser.getBackgold()+ticeng);
			puserService.updateByPrimaryKeySelective(puser);
			logger.info("玩家gameId: "+user.getUid()+", 充值金额: "+ orMoney + ", " + lvl+
					"级代理玩家gameId: "+puser.getUid() +", 获得提成：" +ticeng);
			// 生成提成记录
			Profit profit =new Profit();
			/*profit.setUserId(user.getId());
			profit.setGameId(user.getGameUserId());
			profit.setUserName(user.getUserName());
			profit.setOutUserName(user.getOutUserName());
			profit.setOrId(null);
			profit.setOrNub(cardFlow.getCard());
			profit.setOrMoney(orMoney);
			profit.setProfitSum(ticeng);
			profit.setProfitLevel(lvl.toString());
			profit.setParentUserId(puser.getId());
			profit.setCreateTime(new Date());
			profitService.insertSelective(profit);*/
		//}
		return puser!=null?puser.getFrontUid():null;
	}
	
}
